import datetime
from flask import Blueprint,request,jsonify
import requests

from views.db import db

import json

from utils.jwtc import myjwt

from utils.Make_password import make_password

from utils.myfile import MyFile

from utils.redis import rs

from utils.acl import ACL

import redis

import re

from views.db import db

from utils.acl import  acl

from utils.myfile import get_data

import time

import functools

bp_fiction = Blueprint("fiction",__name__)

# 登录
# @bp_fiction.route('/zlogin', methods=['POST', 'GET'])
# def zlogin():
#     if request.method == 'POST':
#         data = get_data()
#         sql = """select * from user where username = '%s'""" % (data['username'])
#         res = db.get_one(sql)
#         if res['username']:
#             if res['password'] == data['password']:
#                 return jsonify({'code': 200, "mes": "登陆成功", "userid": res['id']})
#             else:
#                 return jsonify({'code': 10010, "mes": "密码错误"})
#         else:
#             return jsonify({'code': 10011, "mes": "账号不存在"})

# 无限极
def xtree(data):
    list = []
    dict = {}
    if data:
        for j in data:
            dict[j['id']] = j

        for i in data:
            if i['pid'] == 0:
                list.append(i)
            else:
                if 'son' not in dict[i['pid']]:
                    dict[i['pid']]['son'] = []
                dict[i['pid']]['son'].append(i)
        return list


@bp_fiction.route('/get_zy')
def get_zy():
    uid = request.args.get('uid')
    sql = """select res.id,res.url,res.name,res.pid from resource as res inner join user_resource as us on res.id = us.resourceid where uid=%d""" % int(
        uid)
    res = db.get_all(sql)
    list = xtree(res)
    return jsonify({'code': 200, "list": list})


# 发布文章
@bp_fiction.route('/add_fiction', methods=['GET', 'POST'])
def add_fiction():
    if request.method == 'POST':
        data = get_data()
        uid = request.args.get('uid')
        date = datetime.datetime.now()
        nowtime = date.strftime("%Y-%m-%d %H:%M:%S")
        sql = """insert into fiction(title,content,uid,status,stime) values('%s','%s',%d,%d,'%s')""" % (
        data['title'], data['content'], int(uid), 1, nowtime)
        db.update(sql)
        db.commit()
        return jsonify({'code': 200})


# 获取我的文章
@bp_fiction.route('/get_fiction')
def get_fiction():
    uid = request.args.get('uid')
    if uid:
        sql = """select * from fiction where uid = %d""" % int(uid)
        res = db.get_all(sql)
        return jsonify({'code': 200, "list": res})
    else:
        sql = """select * from fiction where status = 1"""
        res = db.get_all(sql)
        return jsonify({'code': 200, "list": res})


#通过
@bp_fiction.route('/agreen')
def agreen():
    id = request.args.get('id')
    sql = """update fiction set status=2 where id = %d"""%int(id)
    db.update(sql)
    db.commit()
    sql3 = """select * from fiction where id = %d"""%int(id)
    res = db.get_one(sql3)

    sql2 = """select * from zuser where id = %d"""%int(res['userid'])
    ress = db.get_one(sql2)

    jf = int(ress['jifen']) + 2
    sql1 = """update zuser set  jifen = %d where id = %d"""%(jf,int(res['userid']))
    db.update(sql1)
    db.commit()
    return jsonify({"code":200})

#不通过
@bp_fiction.route('/noagreen')
def noagreen():
    id = request.args.get('id')
    sql = """update fiction set status=3 where id = %d""" % int(id)
    db.update(sql)
    db.commit()
    return jsonify({"code": 200})

@bp_fiction.route('/add_prize',methods = ['POST','GET'])
def add_prize():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into jift(name,price,kc,needjf) values('%s',%d,%d,%d)"""%(data['name'],int(data['price']),int(data['kc']),int(data['needjf']))
        db.update(sql)
        db.commit()
        return jsonify({'code':200})


@bp_fiction.route('/userlogin',methods=['POST'])
def userlogin():

    # 获取用户名密码
    data = get_data()

    # 查询用户信息是否正确
    sql = " select * from euser where name='%s' and password='%s' " % (data['name'],data['password'])
    res = db.get_one(sql)

    resourcelist=[]

    if res:
        role_id = res['role_id']
        
        # 根据角色id查找资源列表
        sql2 = " select * from erole_resources as er left join eresources as e on er.resourceid=e.id where er.role_id=%d " % (int(role_id))

        resourcelist = db.get_all(sql2)

        # 判断role_id是否为2 2为管理员
        if res['role_id'] == 2:

            rs.insert_set('auditlist',res['id'])

    return jsonify({"code":200,"resourcelist":resourcelist,"id":res['id'],'name':res['name']})


@bp_fiction.route('/newsM',methods=['POST'])
def newsM():
    # 获取参数
    data = get_data()
    # 写入小说表
    sql = " insert into enews(title,userid) values ('%s',%d) " % (data['title'],int(data['userid']))
    newsid = db.update(sql)
 
    # 审批 多个审批员
    idlist = rs.find_set('auditlist')
    print(idlist)

    # 定义最小值
    min = 0
    auditid=-1
    if idlist:
        # 遍历
        for (i,index) in idlist:
            # i代表审核人id
            key = 'audit%d'%(int(i))
            count = rs.list_len(key)

            if index == 0:
                min = count
                audit = i

            if min > count:
                min = count
                auditid = i

        if auditid>0:
            # 加入审核人对应的任务列表
            rs.list_push('audit%d'%int(auditid),newsid)
    else:
        return jsonify({"code":10010,'mes':"没有审核员"})

    return jsonify({"code":200})

@bp_fiction.route('/get_news')

def get_news():
    userid = request.args.get('userid')

    sql = """select * from enews where userid = %d""" % int(userid)
    res = db.get_all(sql)
    return jsonify({"code":200,"newslist":res})